package lesson07;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

public class MyTimer {


    private BlockingQueue<MyTalk> queue=new PriorityBlockingQueue<>();
    public  MyTimer() {
        Thread thread =new Thread(()->{
        while (true){
                try {
                    MyTalk talk = queue.take();
                    long newTime = System.currentTimeMillis();
                    if (newTime >= talk.getDelay()) {
                        talk.getRunnable().run();
                    } else {
                        long waitTime = talk.getDelay() - System.currentTimeMillis();
                        queue.put(talk);
                        synchronized (this) {
                            this.wait(waitTime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

        }
        });
        thread.start();
        Thread  thread1=new Thread(()->{
                synchronized (this){
                    this.notifyAll();
                }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        thread1.setDaemon(true);
    }



    public  void schedule(Runnable runnable,long  delay) throws InterruptedException {
        if(runnable==null) throw  new InterruptedException("任务不能为空");
        if(delay<0) throw  new InterruptedException("时间不能为负数");
        MyTalk myTalk=new MyTalk(runnable,delay);
        //放入阻塞队列
        queue.put(myTalk);
        synchronized (this){
            this.notifyAll();
         }
    }
}



class  MyTalk  implements Comparable<MyTalk>{
    private  Runnable runnable;
    private  long delay;

    public MyTalk(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.delay = delay+System.currentTimeMillis();
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getDelay() {
        return delay;
    }

    @Override
    public int compareTo(MyTalk o) {
        if(this.delay<o.delay) return -1;
        else  return 1;
    }
}

